package com.stars.easyms.security.matcher;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
public class EasyMsRequestMatcher {

    private final List<RequestMatcher> matchers = new CopyOnWriteArrayList<>();

    public EasyMsRequestMatcher antMatchers(HttpMethod httpMethod, String... antPatterns) {
        String method = httpMethod == null ? null : httpMethod.toString();
        for (String pattern : antPatterns) {
            this.matchers.add(new AntPathRequestMatcher(pattern, method));
        }
        return this;
    }

    public EasyMsRequestMatcher antMatchers(String... antPatterns) {
        return antMatchers(null, antPatterns);
    }

    public EasyMsRequestMatcher regexMatchers(HttpMethod httpMethod, String... regexPatterns) {
        String method = httpMethod == null ? null : httpMethod.toString();
        for (String pattern : regexPatterns) {
            this.matchers.add(new RegexRequestMatcher(pattern, method));
        }
        return this;
    }

    public EasyMsRequestMatcher regexMatchers(String... regexPatterns) {
        return regexMatchers(null, regexPatterns);
    }

    public boolean matches(HttpServletRequest request) {
        for (RequestMatcher matcher : matchers) {
            if (matcher.matches(request)) {
                return true;
            }
        }
        return false;
    }
}
